package com.yjht.online.generate.impl.person;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.json.JSONUtil;
import com.yjht.online.generate.model.person.PersonModel;
import com.yjht.online.generate.person.PersonGenerateProssor;
import com.yjht.online.util.OnLineFileUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public abstract class PersonGenerateProssorTemplate implements PersonGenerateProssor {

    final static Logger logger = LoggerFactory.getLogger(PersonGenerateProssorTemplate.class);

    @Override
    public void generatePerson(List<PersonModel> personModelList) {
        String templatePath = templatePath();

        templatePath = OnLineFileUtil.getRuningFilePath(templatePath);
        if(!FileUtil.exist(templatePath)){
            logger.error("excel文件模板不存在"+templatePath);
        }

        TemplateExportParams params = new TemplateExportParams(templatePath);

        HashMap<String, Object> map = new HashMap<>();
        List<PersonModel>  personModels = deepCopy(personModelList);
        personModels =  hanlerModel(personModels);
        map.put("users", personModels);
        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
        String outputPath = fullOutputPath();
        File file = OnLineFileUtil.getOutPutFile(outputPath);
        FileUtil.del(file);

        FileUtil.touch(file);

        OutputStream outputStream = FileUtil.getOutputStream(file);
        if(workbook == null){
            logger.error("Excel生成失败");
            return;
        }
        try {
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    private List<PersonModel> deepCopy(List<PersonModel> personModelList){
        if(CollectionUtil.isEmpty(personModelList)){
            return new ArrayList<>();
        }

        String json = JSONUtil.toJsonStr(personModelList);

        return JSONUtil.toList(JSONUtil.parseArray(json),PersonModel.class);
    }
    /**
     * 数据处理
     * 子类不能修改personModels对象
     * @return
     */
    protected abstract List<PersonModel> hanlerModel(List<PersonModel> personModels);

    /**
     * 模板文件路径
     *
     * @return
     */
    protected abstract String templatePath();

    protected abstract String fullOutputPath();

}
